package com.shop.coupon.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.common.core.domain.Result;
import com.shop.common.security.utils.SecurityUtils;
import com.shop.coupon.domain.Coupon;
import com.shop.coupon.domain.CouponHistory;
import com.shop.coupon.mapper.CouponHistoryMapper;
import com.shop.coupon.service.CouponHistoryService;
import com.shop.coupon.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CouponHistoryServiceImpl extends ServiceImpl<CouponHistoryMapper, CouponHistory> implements CouponHistoryService {

    private final CouponHistoryMapper couponHistoryMapper;

    public CouponHistoryServiceImpl(CouponHistoryMapper couponHistoryMapper) {
        this.couponHistoryMapper = couponHistoryMapper;
    }

    @Autowired
    private CouponService couponService;

    /**
     * 新用户注册赠券
     * @param couponHistory
     * @return
     */
    @Override
    public Result couponHistoryGift(CouponHistory couponHistory) {
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        if (couponHistory.getMemberId() != 4){
            couponHistory.setCouponId(4L);
            couponHistory.setMemberId(userId);
            couponHistory.setMemberNickName(username);
            Integer historyGift = couponHistoryMapper.couponHistoryGift(couponHistory);
            return Result.success("新用户优惠券赠送成功"+historyGift);
        }
        return Result.error("此用户已经赠送过");
    }



    /**
     * 手动领取优惠券
     * @param couponHistory
     * @return
     */
    @Override
    public Result couponDrawDown(CouponHistory couponHistory) {
        //查询优惠券详情
        Result<Coupon> selectCoupon = couponService.getCoupon(5L);
        Coupon coupon = selectCoupon.getData();
        //获取当前登陆人的名称
        String username = SecurityUtils.getUsername();
        //获取当前登陆人的id
        Long userId = SecurityUtils.getUserId();
        //当前登陆人id赋值
        couponHistory.setMemberId(userId);
        //获取当前登陆人的优惠券列表
        CouponHistory history = baseMapper.selectById(couponHistory.getMemberId());
        //判断当前卡包里的优惠券id与优惠券列表id是否相同
        if (history.getCouponId() != coupon.getId()){
              couponHistory.setCouponId(coupon.getId());
            couponHistory.setMemberId(userId);
            couponHistory.setMemberNickName(username);
            Integer drawDown = couponHistoryMapper.couponDrawDown(couponHistory);
            return Result.success(drawDown);
        }
        if (coupon.getPerLimit() > history.getNumber()){
            Integer couponNumUpd = couponHistoryMapper.couponNumUpd(history.getId());
            return Result.success(couponNumUpd);
        }
        return Result.error("该优惠券已经领取");
    }
}
